package com.paradise.phone.fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paradise.api.FaceCall;
import com.paradise.phone.OnRecyclerViewItemClickListener;
import com.paradise.phone.R;
import com.paradise.phone.adapter.ContactAdapter;
import com.paradise.phone.bean.ContactBean;
import com.paradise.phone.utils.DataBaseHelper;
import com.paradise.phone.utils.MyItemDecoration;
import com.paradise.phone.utils.PinyinUtils;
import com.paradise.phone.utils.SideBar;
import com.paradise.phone.utils.ToastUtil;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Sisyphus on 2017/9/21.
 */

public class ContactFragment extends Fragment implements View.OnClickListener, OnRecyclerViewItemClickListener {

    private View rootView;
    private ImageView ivNocontact;
    private SQLiteDatabase db;

    private RecyclerView rvContacts;
    private ContactAdapter ca;
    private ArrayList<ContactBean> contacts;

    private ImageView ivAddContact;

    private AlertDialog addContactDialog;

    private SearchView svFindContact;
    private LinearLayout llResult;
    private RecyclerView rvResult;
    private ContactAdapter resultAdapter;
    private ArrayList<ContactBean> result;

    private int itemType = 0;
    private SideBar sideBar;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_contact, null);

        db = DataBaseHelper.instance(getActivity())
                .getWritableDatabase();

        initView();

        initEvent();

        return rootView;
    }

    private void initView() {
        ivNocontact = (ImageView) rootView.findViewById(R.id.iv_no_contact);
        rvContacts = (RecyclerView) rootView.findViewById(R.id.rv_contacts);
        ivAddContact = (ImageView) rootView.findViewById(R.id.iv_add_contact);
        svFindContact = (SearchView) rootView.findViewById(R.id.sv_search_contact);
        llResult = (LinearLayout) rootView.findViewById(R.id.ll_result);
        rvResult = (RecyclerView) rootView.findViewById(R.id.rv_result);
        sideBar = (SideBar) rootView.findViewById(R.id.sideBar);
        rvResult.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvResult.addItemDecoration(new MyItemDecoration());
        rvContacts.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvContacts.addItemDecoration(new MyItemDecoration());

        contacts = getAllContact();
        if (contacts.size() == 0){
            ivNocontact.setVisibility(View.VISIBLE);
        }else {
            ivNocontact.setVisibility(View.INVISIBLE);
            ca = new ContactAdapter();
            ca.addRecyclerViewItemClickListener(this);
            ca.setData(contacts);
            rvContacts.setAdapter(ca);
        }
    }

    private void initEvent() {
        ivNocontact.setOnClickListener(this);
        ivAddContact.setOnClickListener(this);

        svFindContact.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)) {
                    llResult.setVisibility(View.GONE);
                    itemType = 0;
                } else {
                    itemType = 1;
                    result = searchContact(s);
                    llResult.setVisibility(View.VISIBLE);
                    resultAdapter = new ContactAdapter();
                    resultAdapter.addRecyclerViewItemClickListener(ContactFragment.this);
                    resultAdapter.setData(result);
                    rvResult.setAdapter(resultAdapter);
                }

                return false;
            }
        });

        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int count = contacts.size();
                if (s.equals("#")){
                    rvContacts.smoothScrollToPosition(0);
                }else {
                    for (int i = 0; i < count; i++) {
                        if (contacts.get(i).getPinyin().charAt(0) == s.charAt(0)) {
                            rvContacts.smoothScrollToPosition(i);
                            return;
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取所有联系人
     * @return
     */
    private ArrayList<ContactBean> getAllContact() {
        Cursor c = db.rawQuery("select * from Contact order by pinyin", null);
        contacts = new ArrayList<>();
        while (c.moveToNext()) {
            ContactBean cb = new ContactBean();
            cb.setRemarks(c.getString(1));
            cb.setNumber(c.getString(2));
            cb.setCreataTime(c.getString(3));
            cb.setPinyin(c.getString(4));

            contacts.add(cb);
        }

        return contacts;
    }

    /**
     * 检索联系人
     * @param key
     * @return
     */
    private ArrayList<ContactBean> searchContact(String key) {
        String queryString = "select * from Contact where number like '%"
                + key + "%' or remarks like '%" + key + "%'";
        Cursor cursor = db.rawQuery(queryString, null);
        ArrayList<ContactBean> tempContacts = new ArrayList<>();
        if (cursor.getCount() == 0) {
            return tempContacts;
        } else {
            while (cursor.moveToNext()) {
                ContactBean cb = new ContactBean();
                cb.setRemarks(cursor.getString(1));
                cb.setNumber(cursor.getString(2));
                cb.setCreataTime(cursor.getString(3));
                cb.setPinyin(cursor.getString(4));
                tempContacts.add(cb);
            }
            return tempContacts;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_no_contact:

                showDialog();
                break;

            case R.id.iv_add_contact:

                showDialog();
                break;
        }
    }

    /**
     * 显示添加联系人对话框
     */
    private void showDialog() {
        if (addContactDialog == null) {
            View dialogView = LayoutInflater.from(getActivity())
                    .inflate(R.layout.dialog_add_contact, null);
            final EditText etRemarks = (EditText) dialogView.findViewById(R.id.et_add_display_name);
            final EditText etNumber = (EditText) dialogView.findViewById(R.id.et_add_username);
            TextView tvConfirm = (TextView) dialogView.findViewById(R.id.tv_add_confirm);
            TextView tvCancle = (TextView) dialogView.findViewById(R.id.tv_add_cancle);

            tvConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (TextUtils.isEmpty(etRemarks.getText())
                            || TextUtils.isEmpty(etNumber.getText())) {
                        ToastUtil.showToast(getActivity(), "备注或号码为空");
                        return;
                    }

                    ContentValues values = new ContentValues();
                    values.put("remarks", etRemarks.getText().toString());
                    values.put("number", etNumber.getText().toString());
                    String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    values.put("create_time", createTime);
                    String pinyin = null;
                    try {
                        pinyin = new PinyinUtils().hanzi2Pinyin(etRemarks.getText().toString(),
                                        "", PinyinUtils.Type.FIRSTUPPER);
                        values.put("pinyin", pinyin);
                    } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                        badHanyuPinyinOutputFormatCombination.printStackTrace();
                        return;
                    }
                    if (db.insert("Contact", null, values) != -1) {
                        ToastUtil.showToast(getActivity(), "添加成功");

                        ivNocontact.setVisibility(View.INVISIBLE);

                        ContactBean cb = new ContactBean();
                        cb.setRemarks(etRemarks.getText().toString());
                        cb.setNumber(etNumber.getText().toString());
                        cb.setCreataTime(createTime);
                        cb.setPinyin(pinyin);

                        if (contacts == null
                                || db.rawQuery("select * from Contact", null).getCount() == 0) {
                            contacts = new ArrayList<>();
                            contacts.add(cb);
                            ca = new ContactAdapter();
                            ca.addRecyclerViewItemClickListener(ContactFragment.this);
                            ca.setData(contacts);
                            rvContacts.setAdapter(ca);
                            rvContacts.setLayoutManager(new LinearLayoutManager(getActivity()));
                        } else {
                            contacts.add(cb);
                            if (ca != null)
                                ca.notifyItemInserted(contacts.size());
                        }

                        addContactDialog.dismiss();
                    } else {
                        ToastUtil.showToast(getActivity(), "添加失败");
                    }
                }
            });

            tvCancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addContactDialog.dismiss();
                }
            });

            addContactDialog = new AlertDialog.Builder(getActivity())
                    .setView(dialogView)
                    .create();

            addContactDialog.setCancelable(false);
        }

        if (!addContactDialog.isShowing()) {
            addContactDialog.show();
        }
    }

    @Override
    public void onRecyclerViewItemClickLitener(View view, int position) {

        switch (view.getId()) {
            case R.id.tv_contact_call:
                if (itemType == 0) {
                    FaceCall.instance().call(getActivity(),
                            contacts.get(position).getNumber(),
                            contacts.get(position).getRemarks());
                } else {
                    FaceCall.instance().call(getActivity(),
                            result.get(position).getNumber(),
                            result.get(position).getRemarks());
                }
                break;
            case R.id.tv_contact_delete:

                // 如果当前显示的是联系人检索结果列表，删除检索结果同时也删除实际存储联系人
                if (itemType == 1) {

                    if (result.get(position).getNumber().equals(getActivity().getString(R.string.test_num))
                            && result.get(position).getRemarks().equals(getActivity().getString(R.string.test_name))){
                        ToastUtil.showToast(getActivity(), "内置账号，无法删除！");
                        break;
                    }

                    db.execSQL("delete from Contact where number = '" +
                            result.get(position).getNumber()+"'");

                    result.remove(position);
                    resultAdapter.notifyItemRemoved(position);

                    contacts = getAllContact();
                    if (contacts.size() == 0){
                        ivNocontact.setVisibility(View.VISIBLE);
                    }else {
                        ivNocontact.setVisibility(View.INVISIBLE);
                        ca.setData(contacts);
                        rvContacts.setAdapter(ca);
                    }

                } else {

                    if (contacts.get(position).getNumber().equals(getActivity().getString(R.string.test_num))
                            && contacts.get(position).getRemarks().equals(getActivity().getString(R.string.test_name))){
                        ToastUtil.showToast(getActivity(), "内置账号，无法删除！");
                        break;
                    }

                    db.execSQL("delete from Contact where number = '" +
                            contacts.get(position).getNumber()+"'");

                    contacts.remove(position);
                    ca.notifyItemRemoved(position);
                }

                break;
        }
    }
}
